import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class FunctionCall extends AbstractElement {
	
	public FunctionCall(String value) {
		this.type = "Function Call";
		this.value = value;
	}
	
	public FunctionCall() {
		this.type = "Function Call";
	}
	
	public Object interpret(RobotActions robot) {
		Object result = null;
		
		String method_name = null;
		try {
			
			//get robot class
			Class<? extends RobotActions> cls = robot.getClass();
			//object
			Object inst = (Object)robot;
			
			method_name = this.value;
			
			Object params[] = new Object[this.filhos.size()];
			Class partypes[] = new Class[this.filhos.size()];

			//parametros
			for (int i = 0; i < this.filhos.size(); i++) {

				params[i] = this.filhos.get(i).interpret(robot);
				
			}

			Method method = AbstractElement.getMethod(method_name, robot);

				
			result = method.invoke(inst, params);
			
			
			return result;

		} 
		
		
		
		catch (IllegalArgumentException e) {
			System.err.println("FunctionCall.invoke: Method " + method_name + " has different number/type of arguments");
			return null;
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		catch (NullPointerException e) {
			System.err.println("FunctionCall.invoke: There is no such method: " + method_name);
			return null;
		}
		catch (Exception e) {
			System.err.println("FunctionCall.interpret: An unknown error happened while processing a FunctionCall");
			e.printStackTrace();
			return null;
		}
	}

}
